package com.ming.demo.easyiot;

import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import java.io.File;


import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;

/**
 * Created by Administrator on 2016/12/15.
 */
public class UpdateUtil {
    private Context context;
    DownloadManager downloadManager;
    long myDownloadReference;
    BroadcastReceiver mReceiver = null;
    private String ApKURL; //下载apk地址
    private String version_description;

    public UpdateUtil(Context context, String ApKURL, String version_description) {
        this.context = context;
        this.ApKURL = ApKURL;
        this.version_description = version_description;
    }

    public String getVersionName() throws Exception {
        // 获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        String version = packInfo.versionName;
        return version;
    }

    public void showUpdateDialog() {
        final AlertDialog builder = new AlertDialog.Builder(context).create();
        builder.show();
        builder.getWindow().setContentView(R.layout.update_dialog);
        builder.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        //一定得在show完dialog后来set属性
        WindowManager m = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        WindowManager.LayoutParams lp = builder.getWindow().getAttributes();
        lp.width = (int) (d.getWidth() * 0.85);
        builder.getWindow().setAttributes(lp);

        TextView tv_message = (TextView) builder.getWindow().findViewById(R.id.tv_dialog_message);
        tv_message.setText(version_description);
        builder.setCancelable(false);

        LinearLayout dialog_ok = (LinearLayout) builder.getWindow().findViewById(R.id.mLyUpdate);
        dialog_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                //判断是否为同个路径
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    Toast.makeText(context, "正在开始下载",Toast.LENGTH_SHORT).show();
                    downloadDialog();
                    builder.dismiss();
                } else {
                    Toast.makeText(context, "SD卡不可用，请插入SD卡",Toast.LENGTH_SHORT).show();
                }
            }
        });
        LinearLayout dialog_cancel = (LinearLayout) builder.getWindow().findViewById(R.id.mLyCancle);
        dialog_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                builder.dismiss();
            }
        });
    }

    public void downloadDialog() {
        //系统默认的通知栏显示下载的进度条
        String serviceString = context.DOWNLOAD_SERVICE;
        downloadManager = (DownloadManager) context.getSystemService(serviceString);

        Uri uri = Uri.parse(ApKURL);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setTitle("NB-Signal");
        request.setDestinationInExternalPublicDir("download", "NB-Signal.apk");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setMimeType("application/vnd.android.package-archive");
        request.allowScanningByMediaScanner();

        // 设置为可见和可管理

        request.setVisibleInDownloadsUi(true);
        myDownloadReference = downloadManager.enqueue(request);
        IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                if (myDownloadReference == reference) {
//                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {

//                        Uri downloadFileUri = downloadManager.getUriForDownloadedFile(reference);
//                        AutoInstall.setUrl(downloadFileUri);
//                    } else {
                    File apkFile = queryDownloadedApk(context, reference);
                    AutoInstall.setApkFile(apkFile);
                    AutoInstall.install(context);
//                    }
                }
            }
        };
        context.registerReceiver(mReceiver, filter);
    }


    //通过downLoadId查询下载的apk，解决6.0以后安装的问题
    public static File queryDownloadedApk(Context context, long downloadId) {
        File targetApkFile = null;
        DownloadManager downloader = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
//        long downloadId = PreferencesUtils.getLong(context, DownloadActivity.DOWNLOAD_ID);
        if (downloadId != -1) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(downloadId);
            query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
            Cursor cur = downloader.query(query);
            if (cur != null) {
                if (cur.moveToFirst()) {
                    String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                    if (!StringUtil.isNull(uriString)) {
                        targetApkFile = new File(Uri.parse(uriString).getPath());
                    }
                }
                cur.close();
            }
        }
        return targetApkFile;
    }
}
